package com.mobilesales.android.adapters;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.model.clients.Client;
import com.mobilesales.android.model.orders.OrderItem;
import com.mobilesales.android.util.MessageBox;

public class OrderItemAdapter extends ArrayAdapter<OrderItem> {

	private Client client;
	Context context;
	int idlayout;

	public OrderItemAdapter(Context context, int textViewResourceId,
			List<OrderItem> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		idlayout = textViewResourceId;
	}

	public void setClient(Client cli) {
		this.client = cli;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
					"layout_inflater");
			v = vi.inflate(idlayout, null);
		}

		OrderItem orderItem = null;
		if ((position >= 0) && (position < this.getCount())) {
			orderItem = this.getItem(position);
		}

		if (orderItem != null) {
			TextView productNameField = (TextView) v
					.findViewById(R.id.productNameTxt);
			TextView productSkuField = (TextView) v
					.findViewById(R.id.productSkuTxt);
			TextView productQuantityField = (TextView) v
					.findViewById(R.id.productQuantityTxt);
			TextView productPriceField = (TextView) v
					.findViewById(R.id.productPriceTxt);

			double price = orderItem.Product.Price
					* (1 + orderItem.Product.Spread)
					* (1 + orderItem.Product.Tax.Value);
			if (this.client != null)
				price *= (1 - client.Group.Discount);

			productNameField.setText(orderItem.Product.Name);
			productSkuField.setText(orderItem.Product.Sku);
			String productQuantityStr = String.format("%s x %s",
					String.format("%1$,.3f", orderItem.Quantity),
					String.format("%1$,.2f", price));
			productQuantityField.setText(productQuantityStr);
			productPriceField.setText(String.format("%1$,.2f", price
					* orderItem.Quantity));

			v.setOnLongClickListener(new OnLongClickListener() {

				public boolean onLongClick(View v) {
					// TODO Auto-generated method stub
					openEditPopup(position);
					return false;
				}
			});
		}
		return v;
	}

	@Override
	public void add(OrderItem item) {
		for (int i = 0; i < this.getCount(); i++) {
			OrderItem el = this.getItem(i);
			if (el.Product.Id == item.Product.Id) {
				item.Quantity += el.Quantity;
				this.remove(el);
				this.insert(item, i);
				return;
			}
		}
		super.add(item);
	}

	private void openEditPopup(final int position) {
		final OrderItem item = this.getItem(position);
		if (item == null)
			return;
		try {
			Display display = ((WindowManager) context
					.getSystemService(Context.WINDOW_SERVICE))
					.getDefaultDisplay();
			int width = display.getWidth();
			LayoutInflater inflater = (LayoutInflater) this.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			final View layout = inflater
					.inflate(R.layout.order_item_edit, null);
			layout.setBackgroundResource(R.drawable.border_gray_dark);
			final PopupWindow pw = new PopupWindow(layout, width - 10,
					LayoutParams.WRAP_CONTENT, true);

			/* layout, width * 2 / 3, 100,false); */
			pw.showAtLocation(layout, Gravity.CENTER, 0, 0);

			pw.setBackgroundDrawable(context.getResources().getDrawable(
					R.drawable.border_blue_light));

			Button saveBtn = (Button) layout.findViewById(R.id.saveBtn);
			Button deleteBtn = (Button) layout.findViewById(R.id.deleteBtn);
			Button cancelBtn = (Button) layout.findViewById(R.id.cancelBtn);
			final EditText quantityTxt = (EditText) layout
					.findViewById(R.id.quantityTxt);

			//quantityTxt.setText(String.format("%1$,.3f", item.Quantity));

			quantityTxt.setText((int)item.Quantity+"");
			
			cancelBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					pw.dismiss();
				}
			});

			saveBtn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					try {
						double newQuantity = Double.parseDouble(quantityTxt
								.getText().toString());
						remove(item);
						item.Quantity = newQuantity;
						insert(item, position);
						notifyDataSetChanged();
						pw.dismiss();
					} catch (Exception ex) {
						quantityTxt.setError(getContext().getString(
								R.string.ErrorInvalidValue));
					}

				}
			});

			deleteBtn.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					remove(item);
					notifyDataSetChanged();
					pw.dismiss();
				}
			});
		} catch (Exception e) {
			Log.e("openEditPopup", e.getMessage(), e);
		}
	}

	public int getPosition(int orderItemId) {
		for (int i = 0; i < this.getCount(); i++) {
			if (this.getItem(i).Id == orderItemId)
				return i;
		}
		return -1;
	}
}
